document.addEventListener('DOMContentLoaded', function() {
    // 初始化Fabric.js画布
    const canvas = new fabric.Canvas('imageCanvas', {
        backgroundColor: '#f5f5f5',
        preserveObjectStacking: true
    });
    
    // DOM元素
    const imageInput = document.getElementById('imageInput');
    const uploadArea = document.getElementById('uploadArea');
    const imagePreview = document.getElementById('imagePreview');
    const previewPlaceholder = document.querySelector('.preview-placeholder');
    const downloadBtn = document.getElementById('downloadImage');
    const copyBtn = document.getElementById('copyImage');
    const undoBtn = document.getElementById('undoEdit');
    const redoBtn = document.getElementById('redoEdit');
    
    // 编辑历史记录
    let history = [];
    let historyIndex = -1;
    
    // 当前应用的状态
    let currentState = {
        brightness: 0,
        contrast: 0,
        saturation: 0,
        hue: 0,
        sharpen: 0,
        filter: 'none',
        filterIntensity: 100
    };
    
    // 初始化标签页切换
    initTabs();
    
    // 初始化滑块值显示
    initSliders();
    
    // 图片上传处理
    imageInput.addEventListener('change', handleImageUpload);
    uploadArea.addEventListener('dragover', handleDragOver);
    uploadArea.addEventListener('dragleave', handleDragLeave);
    uploadArea.addEventListener('drop', handleDrop);
    
    // 编辑工具事件监听
    document.getElementById('brightness').addEventListener('input', updateFilterValue);
    document.getElementById('contrast').addEventListener('input', updateFilterValue);
    document.getElementById('saturation').addEventListener('input', updateFilterValue);
    document.getElementById('hue').addEventListener('input', updateFilterValue);
    document.getElementById('sharpen').addEventListener('input', updateFilterValue);
    document.getElementById('filterIntensity').addEventListener('input', updateFilterValue);
    
    // 滤镜按钮
    document.querySelectorAll('.filter-btn').forEach(btn => {
        btn.addEventListener('click', applyFilter);
    });
    
    // 操作按钮
    document.getElementById('applyFilters').addEventListener('click', applyAllFilters);
    document.getElementById('resetFilters').addEventListener('click', resetAllFilters);
    document.getElementById('saveImage').addEventListener('click', saveImage);
    downloadBtn.addEventListener('click', downloadImage);
    copyBtn.addEventListener('click', copyImage);
    undoBtn.addEventListener('click', undoEdit);
    redoBtn.addEventListener('click', redoEdit);
    
    // 初始化标签页
    function initTabs() {
        const tabs = document.querySelectorAll('.tool-tab');
        const panes = document.querySelectorAll('.tool-pane');
        
        tabs.forEach(tab => {
            tab.addEventListener('click', function() {
                // 移除所有活动标签
                tabs.forEach(t => t.classList.remove('active'));
                panes.forEach(p => p.classList.remove('active'));
                
                // 激活当前标签
                this.classList.add('active');
                const tabId = this.getAttribute('data-tab');
                document.getElementById(tabId + 'Tab').classList.add('active');
            });
        });
    }
    
    // 初始化滑块值显示
    function initSliders() {
        const sliders = document.querySelectorAll('input[type="range"]');
        sliders.forEach(slider => {
            const valueElement = document.getElementById(slider.id + 'Value');
            if (valueElement) {
                valueElement.textContent = slider.value;
                slider.addEventListener('input', function() {
                    valueElement.textContent = this.value;
                });
            }
        });
    }
    
    // 处理图片上传
    function handleImageUpload(e) {
        const file = e.target.files[0];
        if (file) {
            if (!file.type.match('image.*')) {
                alert('请选择有效的图片文件');
                return;
            }
            
            if (file.size > 5 * 1024 * 1024) {
                alert('图片大小不能超过5MB');
                return;
            }
            
            const reader = new FileReader();
            reader.onload = function(event) {
                loadImageToCanvas(event.target.result);
            };
            reader.readAsDataURL(file);
        }
    }
    
    // 处理拖放
    function handleDragOver(e) {
        e.preventDefault();
        e.stopPropagation();
        uploadArea.classList.add('dragover');
    }
    
    function handleDragLeave(e) {
        e.preventDefault();
        e.stopPropagation();
        uploadArea.classList.remove('dragover');
    }
    
    function handleDrop(e) {
        e.preventDefault();
        e.stopPropagation();
        uploadArea.classList.remove('dragover');
        
        const file = e.dataTransfer.files[0];
        if (file && file.type.match('image.*')) {
            if (file.size > 5 * 1024 * 1024) {
                alert('图片大小不能超过5MB');
                return;
            }
            
            const reader = new FileReader();
            reader.onload = function(event) {
                loadImageToCanvas(event.target.result);
            };
            reader.readAsDataURL(file);
        }
    }
    
    // 加载图片到画布
    function loadImageToCanvas(imageUrl) {
        fabric.Image.fromURL(imageUrl, function(img) {
            // 清除画布
            canvas.clear();
            
            // 设置画布尺寸适应图片
            canvas.setWidth(img.width > 800 ? 800 : img.width);
            canvas.setHeight(img.height > 600 ? 600 : img.height);
            
            // 缩放大图片以适应画布
            if (img.width > 800 || img.height > 600) {
                const scale = Math.min(800 / img.width, 600 / img.height);
                img.scale(scale);
            }
            
            // 添加图片到画布
            canvas.add(img);
            canvas.renderAll();
            
            // 显示画布，隐藏占位符
            document.getElementById('imageCanvas').style.display = 'block';
            previewPlaceholder.style.display = 'none';
            
            // 启用下载和复制按钮
            downloadBtn.disabled = false;
            copyBtn.disabled = false;
            
            // 保存初始状态到历史记录
            saveState();
        }, {
            crossOrigin: 'anonymous'
        });
    }
    
    // 更新滤镜值
    function updateFilterValue() {
        const filterId = this.id;
        const value = this.value;
        
        // 更新当前状态
        currentState[filterId] = parseInt(value);
        
        // 如果是滤镜强度滑块，只更新不应用
        if (filterId !== 'filterIntensity') {
            applyAllFilters();
        }
    }
    
    // 应用滤镜
    function applyFilter() {
        const filterType = this.getAttribute('data-filter');
        
        // 更新当前状态
        currentState.filter = filterType;
        
        // 移除所有滤镜按钮的active类
        document.querySelectorAll('.filter-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        
        // 为当前按钮添加active类
        this.classList.add('active');
        
        // 应用滤镜
        applyAllFilters();
    }
    
    // 应用所有滤镜
    function applyAllFilters() {
        const objects = canvas.getObjects();
        if (objects.length === 0) return;
        
        const image = objects[0];
        
        // 清除现有滤镜
        image.filters = [];
        
        // 应用亮度、对比度、饱和度、色相
        if (currentState.brightness !== 0 || currentState.contrast !== 0 || 
            currentState.saturation !== 0 || currentState.hue !== 0) {
            image.filters.push(
                new fabric.Image.filters.Brightness({
                    brightness: currentState.brightness / 100
                }),
                new fabric.Image.filters.Contrast({
                    contrast: currentState.contrast / 100
                }),
                new fabric.Image.filters.Saturation({
                    saturation: 1 + (currentState.saturation / 100)
                }),
                new fabric.Image.filters.HueRotation({
                    rotation: currentState.hue
                })
            );
        }
        
        // 应用锐化
        if (currentState.sharpen > 0) {
            image.filters.push(
                new fabric.Image.filters.Convolute({
                    matrix: sharpenMatrix(currentState.sharpen)
                })
            );
        }
        
        // 应用滤镜效果
        if (currentState.filter !== 'none') {
            const intensity = currentState.filterIntensity / 100;
            
            switch(currentState.filter) {
                case 'grayscale':
                    image.filters.push(
                        new fabric.Image.filters.Grayscale()
                    );
                    break;
                case 'sepia':
                    image.filters.push(
                        new fabric.Image.filters.Sepia()
                    );
                    break;
                case 'invert':
                    image.filters.push(
                        new fabric.Image.filters.Invert()
                    );
                    break;
                case 'blur':
                    image.filters.push(
                        new fabric.Image.filters.Blur({
                            blur: intensity * 5
                        })
                    );
                    break;
                case 'vintage':
                    // 自定义复古滤镜
                    image.filters.push(
                        new fabric.Image.filters.Sepia(),
                        new fabric.Image.filters.Brightness({
                            brightness: -0.05 * intensity
                        }),
                        new fabric.Image.filters.Contrast({
                            contrast: 0.1 * intensity
                        })
                    );
                    break;
                case 'cool':
                    // 自定义冷色调滤镜
                    image.filters.push(
                        new fabric.Image.filters.HueRotation({
                            rotation: -10 * intensity
                        }),
                        new fabric.Image.filters.Saturation({
                            saturation: 0.8 * intensity
                        })
                    );
                    break;
                case 'warm':
                    // 自定义暖色调滤镜
                    image.filters.push(
                        new fabric.Image.filters.HueRotation({
                            rotation: 10 * intensity
                        }),
                        new fabric.Image.filters.Saturation({
                            saturation: 0.8 * intensity
                        })
                    );
                    break;
            }
        }
        
        // 应用滤镜并渲染
        image.applyFilters();
        canvas.renderAll();
        
        // 保存状态到历史记录
        saveState();
    }
    
    // 锐化矩阵
    function sharpenMatrix(intensity) {
        const factor = intensity / 100;
        return [
            0, -1 * factor, 0,
            -1 * factor, 1 + 4 * factor, -1 * factor,
            0, -1 * factor, 0
        ];
    }
    
    // 重置所有滤镜
    function resetAllFilters() {
        // 重置滑块值
        document.getElementById('brightness').value = 0;
        document.getElementById('contrast').value = 0;
        document.getElementById('saturation').value = 0;
        document.getElementById('hue').value = 0;
        document.getElementById('sharpen').value = 0;
        document.getElementById('filterIntensity').value = 100;
        
        // 更新显示值
        document.getElementById('brightnessValue').textContent = '0';
        document.getElementById('contrastValue').textContent = '0';
        document.getElementById('saturationValue').textContent = '0';
        document.getElementById('hueValue').textContent = '0';
        document.getElementById('sharpenValue').textContent = '0';
        document.getElementById('filterIntensityValue').textContent = '100';
        
        // 重置滤镜按钮
        document.querySelectorAll('.filter-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        document.querySelector('.filter-btn[data-filter="none"]').classList.add('active');
        
        // 重置当前状态
        currentState = {
            brightness: 0,
            contrast: 0,
            saturation: 0,
            hue: 0,
            sharpen: 0,
            filter: 'none',
            filterIntensity: 100
        };
        
        // 应用重置
        applyAllFilters();
    }
    
    // 保存图片
    function saveImage() {
        if (canvas.getObjects().length === 0) {
            alert('请先上传图片');
            return;
        }
        
        // 创建一个临时链接下载图片
        const link = document.createElement('a');
        link.download = 'edited-image.png';
        link.href = canvas.toDataURL({
            format: 'png',
            quality: 1
        });
        link.click();
    }
    
    // 下载图片
    function downloadImage() {
        saveImage();
    }
    
    // 复制图片到剪贴板
    function copyImage() {
        if (canvas.getObjects().length === 0) {
            alert('请先上传图片');
            return;
        }
        
        canvas.getElement().toBlob(function(blob) {
            navigator.clipboard.write([
                new ClipboardItem({
                    [blob.type]: blob
                })
            ]).then(() => {
                alert('图片已复制到剪贴板');
            }).catch(err => {
                alert('复制失败: ' + err);
            });
        });
    }
    
    // 保存状态到历史记录
    function saveState() {
        // 如果当前不是历史记录的最后一个，截断后面的记录
        if (historyIndex < history.length - 1) {
            history = history.slice(0, historyIndex + 1);
        }
        
        // 保存当前画布状态
        history.push(JSON.stringify(canvas.toJSON()));
        historyIndex = history.length - 1;
        
        // 更新撤销/重做按钮状态
        updateUndoRedoButtons();
    }
    
    // 撤销操作
    function undoEdit() {
        if (historyIndex > 0) {
            historyIndex--;
            loadStateFromHistory();
        }
    }
    
    // 重做操作
    function redoEdit() {
        if (historyIndex < history.length - 1) {
            historyIndex++;
            loadStateFromHistory();
        }
    }
    
    // 从历史记录加载状态
    function loadStateFromHistory() {
        canvas.loadFromJSON(history[historyIndex], function() {
            canvas.renderAll();
            updateUndoRedoButtons();
        });
    }
    
    // 更新撤销/重做按钮状态
    function updateUndoRedoButtons() {
        undoBtn.disabled = historyIndex <= 0;
        redoBtn.disabled = historyIndex >= history.length - 1;
    }
});